#include "audiofilewidget.h"
#include "MessageBox.h"
#include "hotkeyedit.h"
#include "models/command.h"
#include "models/databasemanager.h"

#include <MainWindow.h>
#include <QHeaderView>
#include <QLineEdit>
#include <QScroller>
#include <QVBoxLayout>

#include <models/syssettingmodel.h>

AudioFileWidget::AudioFileWidget(QWidget *parent)
    : QWidget{parent}
{
    initUI();
}

AudioFileWidget::~AudioFileWidget()
{
    if(isVisible())
    {
        saveData();
    }
}

void AudioFileWidget::initUI()
{
    // 创建主布局
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(int(10*g_xScale));
    // 创建顶部工具栏
    QWidget* toolbar = new QWidget(this);
    toolbar->setFixedHeight(int(60*g_yScale));
    QHBoxLayout* toolbarLayout = new QHBoxLayout(toolbar);
    toolbarLayout->setContentsMargins(28, 0, 28, 0);
    toolbarLayout->setSpacing(int(20*g_xScale));

    // 创建新增按钮
    m_pNewButton = new TouchButton(tr("新建"),toolbar);
    m_pNewButton->setStyleSheet(QString("QPushButton{\
        background:transparent; \
        color:#007BFF;\
        font:%1px \"微软雅黑\"; \
        border-color: #098CFF;\
        border-width:1px;}\
        QPushButton:pressed{ \
        color:#0056b3;}").arg(int(20*g_xScale)));
    toolbarLayout->addStretch();
    toolbarLayout->addWidget(m_pNewButton);

    //表头样式
    QString headerStyle = QString(
                              "QHeaderView {"
                              "    border: none;"
                              "}"
                              "QHeaderView::section {"
                              "    height: %1px;"
                              "    background-color: #232426;"
                              "    color: white;"
                              "    font: %2px '微软雅黑';"
                              "    border: none;"
                              "    border-bottom: 1px solid #48494E;"
                              "    border-right: 1px solid #48494E;"
                              "    padding-left: 5px;"
                              "}"
                              "QHeaderView::section:last {"
                              "    border-right: none;"
                              "}").arg(int(50 * g_yScale)).arg(int(18*g_xScale));
    // 表格的样式
    QString listStyle = "QTableView {"
                        "    background-color: #232426;"
                        "    border: 1px solid #48494E;"
                        "    color: white;"
                        "    gridline-color: #48494E;"
                        "}";

    m_pList = new QTableWidget(this);
    m_pList->setStyleSheet(listStyle);
    m_pList->setColumnCount(5);
    m_pList->horizontalHeader()->setStyleSheet(headerStyle);
    m_pList->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    m_pList->setHorizontalHeaderLabels(QStringList() << "名称" << "音频文件" << "动作文件" << "快捷键" <<"操作");
    m_pList->setColumnWidth(0, int(300*g_xScale));  // 名称列
    m_pList->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);  // 文件路径
    m_pList->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);  // 文件路径
    m_pList->setColumnWidth(3, int(150*g_xScale));  // 快捷键
    m_pList->setColumnWidth(4, int(200*g_xScale));  // 操作列

    // 设置表头属性
    m_pList->horizontalHeader()->setSectionsClickable(false);   // 禁用表头点击
    m_pList->horizontalHeader()->setFixedHeight(int(50*g_xScale));           // 固定表头高度

    m_pList->verticalHeader()->hide();
    m_pList->verticalHeader()->setDefaultSectionSize(int(50*g_xScale));      // 设置默认行高
    m_pList->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); // 固定行高

    // 禁用水平滚动
    m_pList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_pList->setHorizontalScrollMode(QAbstractItemView::ScrollPerItem);

    // 设置垂直滚动
    m_pList->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    m_pList->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    // 配置触摸滚动
    QScroller::grabGesture(m_pList, QScroller::TouchGesture);
    QScroller::grabGesture(m_pList, QScroller::LeftMouseButtonGesture);
    QScroller *scroller = QScroller::scroller(m_pList);
    QScrollerProperties properties = scroller->scrollerProperties();

    // 禁用水平和垂直方向的过度滚动
    properties.setScrollMetric(QScrollerProperties::HorizontalOvershootPolicy, QScrollerProperties::OvershootAlwaysOff);
    properties.setScrollMetric(QScrollerProperties::VerticalOvershootPolicy, QScrollerProperties::OvershootAlwaysOff);

    // 设置水平方向的拖动距离为0，实际上禁用了水平滚动
    properties.setScrollMetric(QScrollerProperties::DragStartDistance, 0.0);

    scroller->setScrollerProperties(properties);

    mainLayout->addWidget(toolbar);
    mainLayout->addWidget(m_pList);
    connect(m_pNewButton,&QPushButton::clicked,this,[this](){
        AudioFile file;
         addNewRow(file);
    });

    QList<AudioFile>  * fileList = SysSettingModel::getInstance()->audioFileList();
    for(int i = 0; i < fileList->size(); ++i)
    {
        addNewRow((*fileList)[i]);
    }
}

void AudioFileWidget::saveData()
{
    QList<AudioFile> fileList;
    for(int i = 0; i < m_pList->rowCount(); ++i)
    {
        QLineEdit* textEdit = qobject_cast<QLineEdit*>(m_pList->cellWidget(i,0));
        QLineEdit* audioFileEdit = qobject_cast<QLineEdit*>(m_pList->cellWidget(i,1));
        QLineEdit* actionFileEdit = qobject_cast<QLineEdit*>(m_pList->cellWidget(i,2));
        HotKeyEdit* keyEdit = qobject_cast<HotKeyEdit*>(m_pList->cellWidget(i,3));
        if(textEdit&&audioFileEdit&&actionFileEdit&&keyEdit)
        {
            AudioFile file;
            file.nID = i + 1;
            file.strShowText = textEdit->text();
            file.strAudioFile = audioFileEdit->text();
            file.strActionFile = actionFileEdit->text();
            file.nFuncKey = keyEdit->getFuncKey();
            file.nHotKey = keyEdit->getHotKey();
            fileList.push_back(file);
        }
    }
    SysSettingModel::getInstance()->setAudioFileList(fileList);
}

void AudioFileWidget::addNewRow(AudioFile file)
{
    QString editStyle = QString(
                            "QLineEdit {"
                            "    background-color: transparent;"
                            "    border: none;"
                            "    color: white;"
                            "    padding: 5px;"
                            "    font: %1px '微软雅黑';"
                            "}"
                            "QLineEdit:focus {"
                            "   background-color:#232426;"
                            "    border: 1px solid #00A4FF;"
                            "}").arg(int(18*g_xScale));
    QString btnStyle=QString("QPushButton{\
                            background:transparent; \
                            color:#007BFF;\
                            font:%1px \"微软雅黑\"; \
                            border-color: #098CFF;\
                            border-width:1px;}\
                            QPushButton:pressed{ \
                            color:#0056b3; \
                            } \
                            QPushButton:disabled { \
                            color: gray; \
                            }").arg(int(18*g_xScale));
    int nRow = m_pList->rowCount();
    m_pList->insertRow(nRow);
    QLineEdit* textEdit = new QLineEdit(m_pList);
    textEdit->setText(file.strShowText);
    textEdit->setStyleSheet(editStyle);
    textEdit->setValidator(new QRegExpValidator(QRegExp("[\u4e00-\u9fa5a-zA-Z0-9]+"), this));
    m_pList->setCellWidget(nRow,0,textEdit);
    QLineEdit* audioFileEdit = new QLineEdit(m_pList);
    audioFileEdit->setText(file.strAudioFile);
    audioFileEdit->setStyleSheet(editStyle);
    m_pList->setCellWidget(nRow,1,audioFileEdit);
    QLineEdit* actionFileEdit = new QLineEdit(m_pList);
    actionFileEdit->setText(file.strActionFile);
    actionFileEdit->setStyleSheet(editStyle);
    m_pList->setCellWidget(nRow,2,actionFileEdit);
    HotKeyEdit* keyEdit = new HotKeyEdit();
    keyEdit->setKey(file.nFuncKey,file.nHotKey);
    keyEdit->setStyleSheet(editStyle);
    m_pList->setCellWidget(nRow,3,keyEdit);
    // 创建操作按钮容器
    QWidget* buttonWidget = new QWidget(this);
    buttonWidget->setStyleSheet("background-color:#232426;");
    QHBoxLayout* buttonLayout = new QHBoxLayout(buttonWidget);
    buttonLayout->setContentsMargins(0,0,0,0);

    TouchButton* deleteBtn = new TouchButton("删除",buttonWidget);
    deleteBtn->setFixedSize(int(60*g_xScale), int(50*g_xScale));
    connect(deleteBtn, &QPushButton::clicked, this, [=]() {
        QString strName = textEdit->text().trimmed();
        if(strName.length() == 0 || question(MainWindow::getInstance(), tr("确定要删除音频文件\"%1\"？").arg(strName)) == 0)
        {
            m_pList->removeRow(m_pList->indexAt(buttonWidget->pos()).row());
            m_pNewButton->setFocus();
        }
    });
    deleteBtn->setStyleSheet(btnStyle);

    buttonLayout->addStretch();
    buttonLayout->addWidget(deleteBtn);
    buttonLayout->addStretch();
    m_pList->setCellWidget(nRow,4,buttonWidget);
}

void AudioFileWidget::hideEvent(QHideEvent *event)
{
    Q_UNUSED(event)
    saveData();
}
